package com.guaoran.distributed.io.bio.one;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author : guaoran
 * @Description BIO server
 * @date :2019/4/18 20:33
 */
public class BIOServer {
    ServerSocket serverSocket;
    public BIOServer(int port){
        if(port==0)
            port=8080;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("BIO 服务已启动，监听"+port+" 端口");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void listener() throws IOException {
        while (true){
            Socket socket = serverSocket.accept();
            new Thread(new ProcessHandle(socket)).start();
        }
    }
    public static void main(String[] args) throws IOException {
        new BIOServer(8080).listener();
    }
}
class ProcessHandle implements Runnable{
    Socket socket;
    public ProcessHandle(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            byte[] buff = new byte[1024];
            int len = is.read(buff);
            if(len>0){
                System.out.println("处理请求："+new String(buff,0,len)+"\t"+Thread.currentThread().getName());
            }
            is.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
